//
//  XKTradeViewController.m
//  XKJY
//
//  Created by xuyaguang on 2017/1/10.
//  Copyright © 2017年 xiaokang100. All rights reserved.
//

#import "XKTradeViewController.h"
#import "XKTradeHeaderCell.h"
#import "XKTradeBuyAndSellCell.h"
#import "XKTradeMyDealCell.h"
#import "XKTradePendingOrderCell.h"
#import "XKTradeEntrustHeaderView.h"
#import "XKTradeRecordView.h"
#import "XKTradeUserAssetModel.h"
#import "XKTradeHeaderModel.h"

#import <AudioToolbox/AudioToolbox.h>

static NSString *const XKTradeHeaderCellID        = @"XKTradeHeaderCellReuseIdentifier";
static NSString *const XKTradeBuyAndSellCellID    = @"XKTradeBuyAndSellCellReuseIdentifier";
static NSString *const XKTradeMyDealCellID        = @"XKTradeMyDealCellReuseIdentifier";
static NSString *const XKTradePendingOrderCellID  = @"XKTradePendingOrderCellReuseIdentifier";

typedef NS_ENUM(NSInteger, USER_TRADE_RECORD_TYPE) {
    RECORD_NONE = 0,
    RECORD_FINISHED,
    RECORD_UNFINISHED,
    RECORD_BOTH
};

@interface XKTradeViewController () <XKTradeBuyAndSellCellDelegate>

@property (nonatomic, strong) XKTradeHeaderModel            *userModel;
@property (nonatomic, assign) USER_TRADE_RECORD_TYPE        recordType;
@property (nonatomic, assign, getter = isClearData) BOOL    clearData;

@end

@implementation XKTradeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}


#pragma mark - 设置自身UI
- (void)setupUI {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadHeaderUserAssetData];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    self.clearData = NO;
}

#pragma mark 键盘出现
-(void)keyboardWillShow:(NSNotification *)note{
    self.tableView.contentInset = UIEdgeInsetsZero;
}
#pragma mark 键盘消失
-(void)keyboardWillHide:(NSNotification *)note{
    self.tableView.contentInset = UIEdgeInsetsZero;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - 加载用户资产
- (void)loadHeaderUserAssetData {
    NSLog(@"加载用户资产");
    
    @weakify(self);
    [APIManager POSTRequestWith:APIPOSTRequestState_UserAssetData parameters:@{} successBlock:^(NSDictionary *successDict) {
        @strongify(self);
        NSLog(@"%@",[NSString jsonToString:successDict]);
        [UserDefaults setObjectWithData:successDict[@"data"][@"user_currency_money"]];
        [self.tableView.mj_header endRefreshing];
        XKTradeHeaderModel *userHeaderModel = [XKTradeHeaderModel mj_objectWithKeyValues:successDict];
        if (userHeaderModel.data.user_trade.count > 0 && userHeaderModel.data.user_orders.count > 0) {
            self.recordType = RECORD_BOTH;
        } else if (userHeaderModel.data.user_trade.count == 0 && userHeaderModel.data.user_orders.count > 0) {
            self.recordType = RECORD_UNFINISHED;
        } else if (userHeaderModel.data.user_trade.count > 0 && userHeaderModel.data.user_orders.count == 0) {
            self.recordType = RECORD_FINISHED;
        } else if (userHeaderModel.data.user_trade.count == 0 && userHeaderModel.data.user_orders.count == 0) {
            self.recordType = RECORD_NONE;
        }
        self.userModel = userHeaderModel;
        [self.tableView reloadData];

    } failureBlock:^(NSDictionary *failureDict) {
        
    } errorBlock:^(NSError *error) {
        
    }];
}

#pragma mark - 买卖交易
- (void)tradeWithType:(TRADETYPE)type price:(NSString *)price number:(NSString *)number password:(NSString *)password {
    NSLog(@"\n交易类型:%@ 价格:%@ 数量:%@ 密码:%@",type ? @"卖出" : @"买入",price,number,password);
    
    // 实名状态值
    NSString *status = [UserDefaults objectWithKey:@"status"];
    
    // 判断实名状态
    if ([status isEqualToString:@"0"]) {
        [SVProgressHUD showInfoWithStatus:@"请先完成实名认证!"];
        return;
    }
    
    if ([status isEqualToString:@"2"]) {
        [SVProgressHUD showInfoWithStatus:@"实名认证中..."];
        return;
    }
    
    
    
    if (type == TRADETYPE_BUY) {
        @weakify(self);
        [APIManager POSTRequestWith:APIPOSTRequestState_WOSTransactions_In parameters:@{@"buyprice":price, @"buynum":number, @"buypwd":password} successBlock:^(NSDictionary *successDict) {
            @strongify(self);
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            [self loadHeaderUserAssetData];
            self.clearData = YES;
            [SVProgressHUD showSuccessWithStatus:successDict[@"msg"]];
            [MobClick event:@"WOSTradeSuccess"]; // 友盟事件统计
        } failureBlock:^(NSDictionary *failureDict) {
            [MobClick event:@"WOSTradeFail"]; // 友盟事件统计
        } errorBlock:^(NSError *error) {
            
        }];
    
    } else if (type == TRADETYPE_SELL) {
        
        @weakify(self);
        [APIManager POSTRequestWith:APIPOSTRequestState_WOSTransactions_Out parameters:@{@"sellprice":price, @"sellnum":number, @"sellpwd":password} successBlock:^(NSDictionary *successDict) {
            @strongify(self);
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            [self loadHeaderUserAssetData];
            self.clearData = YES;
            [SVProgressHUD showSuccessWithStatus:successDict[@"msg"]];
            [MobClick event:@"WOSTradeSuccess"]; // 友盟事件统计
        } failureBlock:^(NSDictionary *failureDict) {
            [MobClick event:@"WOSTradeFail"]; // 友盟事件统计
        } errorBlock:^(NSError *error) {
            
        }];

    }

}


#pragma mark - 取消委托
- (void)cancelOrderWithOrderID:(NSNumber *)order_id {
    
    @weakify(self);
    [UIAlertController showAlertView:self title:@"您确定要撤销委托吗?" message:@"" cancelButtonTitle:@"取消" confirmBtnTitle:@"撤销" cancleBlock:^{
        return;
    } confirmBlock:^{
        @strongify(self);
        [self confirmCancelOrderWithOrderID:order_id];
    }];
}

#pragma mark - 确定取消挂单
- (void)confirmCancelOrderWithOrderID:(NSNumber *)order_id {
    @weakify(self);
    [APIManager POSTRequestWith:APIPOSTRequestState_RevokTradeOrder parameters:@{@"order_id":order_id} successBlock:^(NSDictionary *successDict) {
        @strongify(self);
        [self loadHeaderUserAssetData];
        [SVProgressHUD showSuccessWithStatus:successDict[@"msg"]];
    } failureBlock:^(NSDictionary *failureDict) {
        
    } errorBlock:^(NSError *error) {
        
    }];
}


#pragma mark - 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.recordType == RECORD_NONE) {
        return 2;
    } else if (self.recordType == RECORD_UNFINISHED || self.recordType == RECORD_FINISHED) {
        return 3;
    } else {
        return 4;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ((section == 2) && (self.recordType == RECORD_UNFINISHED || self.recordType == RECORD_FINISHED)) {
        return MAX(self.userModel.data.user_trade.count, self.userModel.data.user_orders.count);
    } else if(section == 2 && self.recordType == RECORD_BOTH) {
        return self.userModel.data.user_orders.count;
    } else if(section == 3){
        return self.userModel.data.user_trade.count;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        XKTradeHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:XKTradeHeaderCellID];
        if (cell == nil) {
            cell = [[XKTradeHeaderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:XKTradeHeaderCellID];
        }
        cell.currencyModel = self.userModel.data.user_currency_money;
        return cell;
    } else if (indexPath.section == 1) {
        XKTradeBuyAndSellCell *cell = [tableView dequeueReusableCellWithIdentifier:XKTradeBuyAndSellCellID];
        if (cell == nil) {
            cell = [[XKTradeBuyAndSellCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:XKTradeBuyAndSellCellID];
        }
        if (self.clearData) {
            [cell clearData];
        }
        self.clearData = NO;
        cell.delegate = self;
        return cell;
    } else if ((indexPath.section == 2) && (self.recordType == RECORD_UNFINISHED || self.recordType == RECORD_BOTH)) {
        XKTradePendingOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:XKTradePendingOrderCellID];
        if (cell == nil) {
            cell = [[XKTradePendingOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:XKTradePendingOrderCellID];
        }
        cell.userOrderModel = self.userModel.data.user_orders[indexPath.row];
        @weakify(self);
        cell.CancelOrderBlock = ^(NSNumber *order_id) {
            @strongify(self);
            [self cancelOrderWithOrderID:order_id];
        };
        return cell;
    }  else {
        
        XKTradeMyDealCell *cell = [tableView dequeueReusableCellWithIdentifier:XKTradeMyDealCellID];
        if (cell == nil) {
            cell = [[XKTradeMyDealCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:XKTradeMyDealCellID];
        }
        cell.userTradeModel = self.userModel.data.user_trade[indexPath.row];
        return cell;
    }
}


#pragma mark - 代理方法
// cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section >= 2) {
        return 65*Scale_H;
    } else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 2 && (self.recordType == RECORD_UNFINISHED || self.recordType == RECORD_BOTH)) {
        XKTradeEntrustHeaderView *entrustView = [XKTradeEntrustHeaderView new];
        entrustView.frame = CGRectMake(0, 0, Main_Width, 100);
        return entrustView;
    } else {
        XKTradeRecordView *recoderView = [XKTradeRecordView new];
        recoderView.frame = CGRectMake(0, 0, Main_Width, 100);
        return recoderView;
    }
}

@end
